from django.shortcuts import render
from django.views import View
import pandas as pd
from django.http import JsonResponse, request
from game.models import ranking

def index(request):
    return render(request,'index.html')

def rank(request):
    return render(request,'rank.html')


class upload_score(View):
    def post(self, request):
        # 参数
        name = request.POST.get('name')
        score = request.POST.get('score')
        # 判断是否存在
        data = ranking.objects.filter(name=name)
        if data.exists():
            ranking.objects.filter(name=name).update(score=score)
        else:
            ranking.objects.create(name=name,score=score)
        # return JsonResponse({'code':200, 'message':'写入成功！'})
        return render(request,'index.html',context={'code': 200, 'message': '写入成功！'})


class rangking_list(View):
    def post(self, request):
        # 参数
        name = request.POST.get('name')
        start = int(request.POST.get('start'))
        end = int(request.POST.get('end'))
        # 获取排行表
        try:
            sql_datas = ranking.objects.values('name','score').filter(name__isnull=False).order_by('-score')
        except Exception as e:
            return JsonResponse({
                'code': 0,
                'message': '查询错误',
            })

        datas_all = pd.DataFrame(sql_datas)
        # 获取查询区间数据
        datas = datas_all[start - 1:end]
        # 获取自己的排名信息
        self_data = datas_all[datas_all['name'] == name]
        self_num = int(datas_all.index[datas_all['name'] == name][0]) + 1
        # 生成排名数组
        rank_num = list(range(start, end + 1))
        rank_num.append(self_num)
        rank_num = pd.DataFrame(rank_num)
        # 数据与排名合并
        datas = pd.concat([datas, self_data], axis=0)
        datas = datas.reset_index(drop=True)
        datas = pd.concat([rank_num,datas], axis=1)
        # 返回
        # return JsonResponse({'code':200, 'message':'查询成功','data':datas.values.tolist()})
        return render(request, 'rank.html', context={'code':200, 'message':'查询成功','data':datas.values.tolist()})